import { Injectable } from '@angular/core';
import { FetchService } from '../../../core/net/fetch.service';
import * as moment from 'moment';
import * as _ from 'lodash';
import { CropsPlanRes, InletPlanRes, InletPlanTableModel } from './year-plan.model';
import { Observable } from 'rxjs';

export const InletPropsHash = {
    'canal': '干渠引水量',
    'agriculture': '农业',
    'reiver': '湖泊湿地',
    'migrate': '生态移民',
    'normal': '生活',
    'productsRatio': '商品率(%)',
    'industry': '工业'
};
export const InletSubmitHash = {
    mar: '3',
    apr: '4',
    may: '5',
    jun: '6',
    jul: '7',
    aug: '8',
    sept: '9',
    octnov: '1011'
};
export const CropsPropsHash = {
    corn: '玉米',
    forestGrass: '林草地',
    fruitsVegetables: '果蔬',
    grape: '葡萄',
    greenhou: '设施温棚',
    irrArea: '灌溉面积',
    mainTotal: '主要作物小计',
    other: '其他',
    otherTotal: '其他作物小计',
    rice: '水稻',
    waterSave: '高效节水',
    wheat: '小麦',
    wolfberry: '枸杞'
};
const CropsData = [
    {
        'id': 8,
        'manageId': 1,
        'areaId': 1,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 3834,
        'rice': 12146,
        'corn': 46257,
        'otherTotal': 34761,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '青铜峡市'
    },
    {
        'id': 9,
        'manageId': 1,
        'areaId': 2,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 12195,
        'rice': 9458,
        'corn': 57938,
        'otherTotal': 20951,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '永宁县'
    },
    {
        'id': 10,
        'manageId': 1,
        'areaId': 3,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 2265,
        'rice': 0,
        'corn': 2760,
        'otherTotal': 19628,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '兴庆区'
    },
    {
        'id': 11,
        'manageId': 1,
        'areaId': 4,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 4902,
        'rice': 9075,
        'corn': 16473,
        'otherTotal': 9690,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '金凤区'
    },
    {
        'id': 12,
        'manageId': 1,
        'areaId': 5,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 0,
        'rice': 15315,
        'corn': 16107,
        'otherTotal': 2143,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '西夏区'
    },
    {
        'id': 13,
        'manageId': 1,
        'areaId': 6,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 50528,
        'rice': 117305,
        'corn': 83784,
        'otherTotal': 79674,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '贺兰县'
    },
    {
        'id': 14,
        'manageId': 1,
        'areaId': 7,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 59455,
        'rice': 106708,
        'corn': 94319,
        'otherTotal': 49842,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '平罗县'
    },
    {
        'id': 15,
        'manageId': 1,
        'areaId': 8,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 7950,
        'rice': 0,
        'corn': 29160,
        'otherTotal': 30840,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '大武口区'
    },
    {
        'id': 16,
        'manageId': 1,
        'areaId': 9,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 19725,
        'rice': 0,
        'corn': 42510,
        'otherTotal': 21954,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '惠农区'
    },
    {
        'id': 17,
        'manageId': 1,
        'areaId': 1,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 880,
        'rice': 5780,
        'corn': 38302,
        'otherTotal': 179621,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '青铜峡市'
    },
    {
        'id': 18,
        'manageId': 1,
        'areaId': 2,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 9400,
        'rice': 0,
        'corn': 65521,
        'otherTotal': 160785,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '永宁县'
    },
    {
        'id': 19,
        'manageId': 1,
        'areaId': 4,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 2600,
        'rice': 0,
        'corn': 14000,
        'otherTotal': 7400,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '金凤区'
    },
    {
        'id': 20,
        'manageId': 1,
        'areaId': 5,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 8578,
        'rice': 28622,
        'corn': 138686,
        'otherTotal': 91097,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '西夏区'
    },
    {
        'id': 21,
        'manageId': 1,
        'areaId': 6,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 7958,
        'rice': 200,
        'corn': 33694,
        'otherTotal': 17744,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '贺兰县'
    },
    {
        'id': 22,
        'manageId': 1,
        'areaId': 7,
        'irrArea': null,
        'mainTotal': null,
        'wheat': 240,
        'rice': 0,
        'corn': 1960,
        'otherTotal': 0,
        'fruitsVegetables': null,
        'grape': null,
        'wolfberry': null,
        'forestGrass': null,
        'greenhou': null,
        'other': null,
        'waterSave': null,
        'dataType': 1,
        'reportYear': '2020',
        'status': 2,
        'areaName': '平罗县'
    }
];

@Injectable({
    providedIn: 'root'
})
export class YearPlanService {

    constructor(private fetchService: FetchService) {
    }

    /**
     * 获取需配水计划-年计划-引黄干渠引水计划查询
     */
    getInletPlanData(date: Date): Promise<Array<InletPlanTableModel>> {
        return new Promise(resolve => {
            let rows: Array<InletPlanTableModel> = [];
            this.fetchService.post<Array<InletPlanRes>>('plan/wrsScheduleCanalFromHuangheHistory/queryInfo', {
                year: moment(date).year()
            }).subscribe(list => {
                if (list.length > 0) {
                    rows = _.compact(Object.keys(list[0]).map((key, index) => {
                        if (Object.keys(InletPropsHash).indexOf(key) >= 0) {
                            return {
                                id: index,
                                name: InletPropsHash[key],
                                props: key,
                                last3year: null,
                                last2year: null,
                                last1year: null,
                                mar: null,
                                apr: null,
                                may: null,
                                jun: null,
                                jul: null,
                                aug: null,
                                sept: null,
                                octnov: null
                            };
                        }
                    }));
                    const paramsHash = {
                        last3year: {
                            'type': 2,
                            'year': moment(date).year() - 3
                        },
                        last2year: {
                            'type': 2,
                            'year': moment(date).year() - 2
                        },
                        last1year: {
                            'type': 2,
                            'year': moment(date).year() - 1
                        },
                        mar: {'type': 1, 'stEdTime': '3'},
                        apr: {'type': 1, 'stEdTime': '4'},
                        may: {'type': 1, 'stEdTime': '5'},
                        jun: {'type': 1, 'stEdTime': '6'},
                        jul: {'type': 1, 'stEdTime': '7'},
                        aug: {'type': 1, 'stEdTime': '8'},
                        sept: {'type': 1, 'stEdTime': '9'},
                        octnov: {'type': 1, 'stEdTime': '1011'}
                    };
                    rows.forEach(item => {
                        Object.keys(paramsHash).forEach(paramsKey => {
                            item[paramsKey] = this.getDataOrNull(list, paramsHash[paramsKey], item.props);
                        });
                    });
                }
                resolve(rows);
            });
        });
    }

    /**
     * 获取年计划-引黄干渠引水计划修改提交数据
     * @param list
     * @param date
     */
    getInletPlanSubmitData(list: Array<InletPlanTableModel>, date: Date): Array<InletPlanRes> {
        return Object.keys(InletSubmitHash).map(key => {
            return {
                canal: _.find(list, {props: 'canal'})[key],
                agriculture: _.find(list, {props: 'agriculture'})[key],
                reiver: _.find(list, {props: 'reiver'})[key],
                migrate: _.find(list, {props: 'migrate'})[key],
                normal: _.find(list, {props: 'normal'})[key],
                productsRatio: _.find(list, {props: 'productsRatio'})[key],
                industry: _.find(list, {props: 'industry'})[key],
                stEdTime: InletSubmitHash[key],
                year: moment(date).year(),
                type: 1,
                manageId: 1
            };
        });
    }

    /**
     * 提交年计划-引黄干渠引水计划数据
     * @param data
     */
    submitInletPlanData(data: Array<InletPlanRes>): Observable<any> {
        return this.fetchService.post<Array<InletPlanRes>>('plan/wrsScheduleCanalFromHuangheHistory/batchEdit', data);
    }

    /**
     * 计算干渠引黄计划 合计、小计值
     * @param arr
     */
    calcInletTotalData(arr: Array<InletPlanTableModel>): Array<InletPlanTableModel> {
        return arr.map(data => {
            const summerTotal = parseFloat((data.mar || 0).toString())
                + parseFloat((data.apr || 0).toString())
                + parseFloat((data.may || 0).toString())
                + parseFloat((data.jun || 0).toString())
                + parseFloat((data.jul || 0).toString())
                + parseFloat((data.aug || 0).toString())
                + parseFloat((data.sept || 0).toString());
            const res = {
                ...data,
                totalYear: summerTotal + parseFloat((data.octnov || 0).toString()),
                totalSummer: summerTotal
            };
            const obj: InletPlanTableModel = {
                id: null,
                name: null,
                props: null,
                last3year: null,
                last2year: null,
                last1year: null,
                totalYear: null,
                totalSummer: null,
                mar: null,
                apr: null,
                may: null,
                jun: null,
                jul: null,
                aug: null,
                sept: null,
                octnov: null
            };
            Object.keys(obj).forEach(key => {
                obj[key] = res[key];
            });
            return obj;
        });
    }

    /**
     * 获取需配水计划-年计划-种植结构及面积查询
     */
    getCropsPlanData(date: Date): Promise<Array<any>> {
        return new Promise(resolve => {
            this.fetchService.post<{ scheduleList: Array<CropsPlanRes>, [key: string]: any }>('base/wrsScheduleCropStructureIrrArea/list', {
                manageId: 1, // 跃进渠针对宁西公司 manageId 默认默认都是1
                reportYear: moment(date).year()
            }).subscribe(resp => {
                const list = resp.scheduleList;
                list.forEach((obj, index) => {
                    obj['dataTypeName'] = obj.dataType === 1 ? '夏秋灌' : '冬灌';
                    obj['id'] = index;
                });
                resolve(list);
            });
        });
    }

    /**
     * 提交年计划-种植结构及面积数据
     * @param data
     */
    submitCropsData(data: Array<CropsPlanRes>): Observable<any> {
        return this.fetchService.post<Array<CropsPlanRes>>('base/wrsScheduleCropStructureIrrArea/batchEdit', data);
    }

    /**
     * 获取表中数值 数字 / null
     * @param data
     * @param pred 断言
     * @param props 属性名
     */
    private getDataOrNull(data: Array<any>, pred, props): number | null {
        return _.find(data, pred) ? _.find(data, pred)[props] : null;
    }
}
